package com.alm.token.ui.activity;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alm.token.ConStant;
import com.alm.token.GlideApp;
import com.alm.token.MyApp;
import com.alm.token.R;
import com.alm.token.base.BaseActivity;
import com.alm.token.base.BaseAdapter;
import com.alm.token.common.RefreshLoadMoreManager;
import com.alm.token.ui.data.bean.ChannelTypeData;
import com.alm.token.ui.data.bean.DrawIndexData;
import com.alm.token.ui.data.bean.LeHuoBaoListData;
import com.alm.token.ui.data.bean.MiningWalletTypeIndexData;
import com.alm.token.ui.data.bean.RegisterData;
import com.alm.token.ui.data.bean.StakingMiningMoneyDrawIndexData;
import com.alm.token.ui.data.bean.StakingOrderAddData;
import com.alm.token.ui.data.bean.StakingOrderAppendData;
import com.alm.token.ui.data.bean.StakingOrderHistoryData;
import com.alm.token.ui.data.bean.UserWalletData;
import com.alm.token.ui.persenter.MyPreenter;
import com.alm.token.ui.view.StakingView;
import com.alm.token.utils.ActionBarHelper;
import com.alm.token.utils.CommonUtil;
import com.alm.token.utils.EmptyUtils;
import com.alm.token.widget.CustomTabLayout;
import com.alm.token.widget.FullyLinearLayoutManager;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CurrencyStakingDetailActivity extends BaseActivity implements StakingView<StakingOrderHistoryData> {


    @BindView(R.id.img_currency_cion)
    ImageView imgCurrencyCion;
    @BindView(R.id.tv_keyongmoney)
    TextView tvKeyongmoney;
    @BindView(R.id.tab)
    CustomTabLayout tab;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.tv_clickreload)
    TextView tvClickreload;
    @BindView(R.id.nodatashow_body)
    RelativeLayout nodatashowBody;
    @BindView(R.id.scroll_view)
    NestedScrollView scrollView;
    @BindView(R.id.tv_transferout)
    LinearLayout tvTransferout;


    MiningWalletTypeIndexData.DataBean data1;

    private RefreshLoadMoreManager<StakingOrderHistoryData.DataBean.ListBean> manager;
    private List<MiningWalletTypeIndexData.DataBean.ChannelListBean> channelListBeans = new ArrayList<>();//name : 锁仓
    private List<MiningWalletTypeIndexData.DataBean.IncomeTypeListBean> incomeTypeListBeans = new ArrayList<>();//name : 收入
    private List<StakingOrderHistoryData.DataBean.ListBean> dataBeanList = new ArrayList<>();

    private int channelListBeansType, incomeTypeListBeansType;

    private String orderSn, limit, page, channelType, incomeType, moneyType;
    private String tabName1, tabName3;

    @Override
    protected MyPreenter initPreenter() {
        return new MyPreenter(this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_staking_currency_detail;
    }

    @Override
    protected void initVariables() {
        UserWalletData.DataBean.WalletsBean item = (UserWalletData.DataBean.WalletsBean) getIntent().getSerializableExtra("WalletsBean");
//        data1 = (MiningWalletTypeIndexData.DataBean) getIntent().getSerializableExtra("MiningWalletTypeIndexData");

        moneyType = String.valueOf(item.getId());
        new ActionBarHelper(this).setTitle(item != null && !item.getName().isEmpty() ? item.getName() : getString(R.string.currency_hint_title1)).setRightIcon(R.drawable.icon_trounout_top1)
                .setRightListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(CurrencyStakingDetailActivity.this, StakingTransformActivity.class);
                        intent.putExtra("moneyType", moneyType);
                        startActivity(intent);
                    }
                });

        GlideApp.with(this).load(item.getLogo()).error(R.drawable.icon_arctic)
                .into(imgCurrencyCion);
        tvTransferout.setBackground(getResources().getDrawable(R.drawable.grey_btn_bg1));
        tvTransferout.setTag(99);
    }

    @Override
    protected void initViews() {

        if (EmptyUtils.isNotEmpty(data1)) {
            tvKeyongmoney.setText(CommonUtil.saveToPoint4WithNo(data1.getMoney()));

            if (data1 != null) {
                MiningWalletTypeIndexData.DataBean.ChannelListBean bean = new MiningWalletTypeIndexData.DataBean.ChannelListBean();
                bean.setName(getString(R.string.profile_hint_item11));
                bean.setType(0);
                channelListBeans.clear();
                channelListBeans.add(0, bean);
                channelListBeans.addAll(data1.getChannelList());

                MiningWalletTypeIndexData.DataBean.IncomeTypeListBean bean2 = new MiningWalletTypeIndexData.DataBean.IncomeTypeListBean();
                bean2.setName(getString(R.string.profile_hint_item11));
                bean2.setType(0);
                incomeTypeListBeans.clear();
                incomeTypeListBeans.add(0, bean2);
                incomeTypeListBeans.addAll(data1.getIncomeTypeList());
            }

            orderSn = "";
            limit = "100";
            page = "1";
            channelType = channelListBeans != null && channelListBeans.size() != 0 ? channelListBeans.get(0).getType() + "" : "";
            incomeType = incomeTypeListBeans != null && incomeTypeListBeans.size() != 0 ? incomeTypeListBeans.get(0).getType() + "" : "";


            String[] tabNames = {channelListBeans != null && channelListBeans.size() != 0 ? channelListBeans.get(0).getName() : getString(R.string.profile_hint_item11),
                    incomeTypeListBeans != null && incomeTypeListBeans.size() != 0 ? incomeTypeListBeans.get(0).getName() + "" : getString(R.string.profile_hint_item11)};
            tabName1 = tabNames[0];
            tabName3 = tabNames[1];
            tab.setItemLayout(R.layout.item_income_expend_tab);
            tab.setTabNames(tabNames);
            tab.setTabCall(new CustomTabLayout.TabCall() {
                @Override
                public void item(int position, FrameLayout frameLayout) {
                    if (position == 0) {
                        showPopupMenu1(frameLayout);
                    } else if (position == 1) {
                        showPopupMenu3(frameLayout);
                    }
                }
            });
            tab.notifyChange();

            initManager();
            recyclerView.setVisibility(View.GONE);
            nodatashowBody.setVisibility(View.VISIBLE);
            scrollView.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_MOVE:
                            break;

                        case MotionEvent.ACTION_DOWN:
                            break;

                        case MotionEvent.ACTION_UP:
                            //当文本的measureheight 等于scroll滚动的长度+scroll的height
                            if (scrollView.getChildAt(0).getMeasuredHeight() <= scrollView.getScrollY() + scrollView.getHeight()) {
                                showWaitDialog();
                                preenter.getStakingOrderIncomeListData(orderSn, limit, page, channelType, incomeType, moneyType);
                            } else {

                            }
                            break;

                    }
                    return false;
                }
            });
        }
    }

    private void initManager() {
        IncomeAdapter adapter = new IncomeAdapter(this);
        manager = new RefreshLoadMoreManager.Builder(this)
                .setAdapter(adapter)
                .setRecyclerView(recyclerView)
                .setLayoutManager(new FullyLinearLayoutManager(this))
                .setOnListItemClickListener(new RefreshLoadMoreManager.OnListItemClickListener() {
                    @Override
                    public void onListItemClick(BaseAdapter.BaseItem item, int position) {
//                        if (dataBeansGuanbi != null && dataBeansGuanbi.size() > position) {
//                            Intent intent = new Intent(QuantitativeOrderCloseListActivity.this, QuantitativeOrderDetailActivity.class);
//                            intent.putExtra("databean", dataBeansGuanbi.get(position));
//                            startActivityForResult(intent, ActivityForResultCode);
//                        }
//                        startActivity(QuantitativeOrderDetailActivity.class);
                    }
                })
//                .setSwipeRefreshLayout(swipeRefreshLayout)
//                .setOnRefreshListener(new RefreshLoadMoreManager.OnRefreshListener() {
//                    @Override
//                    public void onRefresh() {
////                        showToast("onRefresh");
//                        swipeRefreshLayout.setRefreshing(false);
//                        preenter.getLeHuoBaoListData(orderSn, limit, page, channelType, moneyType, incomeType);
//                    }
//                })

                .build();
//         .setOpenLoadMore(true)
//                .setOnLoadMoreListener(new RefreshLoadMoreManager.OnLoadMoreListener() {
//
//                    @Override
//                    public void onLoadMore() {
//                        manager.getAdapter().loadMoreEnd(true);
//                        manager.getAdapter().loadMoreFail();
////                        if(dataBeans.size()!=9){
////                            dataBeans.clear();
////                        }
//                        showWaitDialog();
////                        loadMoreData(ticker);
//                        preenter.getLeHuoBaoListData(orderSn, limit, page, channelType, moneyType, incomeType);
//
//                    }
//                })
        recyclerView.setNestedScrollingEnabled(false);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                if (EmptyUtils.isNotEmpty(dataBeanList) && dataBeanList.size() > position) {
//                    Intent intent = new Intent(CurrencyStakingDetailActivity.this, LogDetailActivity.class);
//                    intent.putExtra("LogDetailActivity_type", LogDetailActivity.BILL_TYPE);
//                    intent.putExtra("LogDetailActivity_id", dataBeanList.get(position).getId());
//                    startActivity(intent);
//                }
            }
        });
    }


    @OnClick({R.id.tv_transferout,R.id.tv_clickreload})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_transferout:
                ShowProgress();
                preenter.getDrawIndexData("51");

//                startActivity(TurnOutActivity.class);
                break;
            case R.id.tv_clickreload:
                mathRequest();
                break;
        }

    }

    public void mathRequest() {
        if (EmptyUtils.isNotEmpty(data1)) {
            limit = "100";
            page = "1";
            dataBeanList.clear();
            preenter.getStakingOrderIncomeListData(orderSn, limit, page, channelType, incomeType, moneyType);
        } else {
            ShowProgress();
            preenter.getMiningWalletTypeIndexData(moneyType);//4 mbtc
        }
    }

    @Override
    protected void loadData() {
        /**
         * @param orderSn     量化订单id
         * @param limit       条数 100
         * @param page        页数  1
         * @param channelType 收益类型，全部传null值
         * @param moneyType   金额类型
         * @param incomeType  收入支出类型
         */
        if (EmptyUtils.isNotEmpty(data1)) {
            orderSn = "";
            limit = "100";
            page = "1";
            channelType = "";

            incomeType = "";
            preenter.getStakingOrderIncomeListData(orderSn, limit, page, channelType, incomeType, moneyType);
        } else {
            ShowProgress();
            preenter.getMiningWalletTypeIndexData(moneyType);//4 mbtc
        }
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    private boolean isfull = false;
    private List<StakingOrderHistoryData.DataBean.ListBean> dataBeanListold = new ArrayList<>();

    @Override
    public void getMiningWalletTypeIndexData(MiningWalletTypeIndexData miningWalletTypeIndexData) {
        if (miningWalletTypeIndexData.getStatus() == 0) {
            if (EmptyUtils.isEmpty(data1)) {
                data1 = miningWalletTypeIndexData.getData();
                initViews();
                loadData();
                tvTransferout.setBackground(getResources().getDrawable(R.drawable.shape_btnbgd_solkie));
                tvTransferout.setTag(null);
            } else {
                data1 = miningWalletTypeIndexData.getData();
                tvKeyongmoney.setText(CommonUtil.saveToPoint4WithNo(data1.getMoney()));
            }

        }
    }

    @Override
    public void getDrawIndexData(Object o) {
        if (o instanceof DrawIndexData && o != null) {
            DrawIndexData.DataBean dataBean = ((DrawIndexData) o).getData();
            MyApp.setDrawIndexDataBean(dataBean);

            if (MyApp.getDrawIndexDataBean() != null) {
                Intent intent = new Intent(this, TurnOutActivity.class);
                intent.putExtra("bizhongtype", "51");
                startActivity(intent);
            }
        }
    }

    @Override
    public void getData(StakingOrderHistoryData stakingOrderHistoryData) {
        preenter.getMiningWalletTypeIndexData(moneyType);//4 mbtc
        if (stakingOrderHistoryData.getStatus() == 0) {
            if (EmptyUtils.isNotEmpty(stakingOrderHistoryData.getData()) &&
                    EmptyUtils.isNotEmpty(stakingOrderHistoryData.getData().getList())) {
                List<StakingOrderHistoryData.DataBean.ListBean> list = stakingOrderHistoryData.getData().getList();

                if (Integer.valueOf(page) == 1) {
                    dataBeanList.clear();
                } else if (!isfull && dataBeanList.size() > (Integer.valueOf(page) - 1) * 100) {
                    dataBeanList.removeAll(dataBeanListold);
                }
//            dataBeanList.clear();
                if (list.size() == 100) {
                    isfull = true;
                    page = String.valueOf(Integer.valueOf(page) + 1);
                } else {
                    isfull = false;
                }

                dataBeanListold = list;
                for (int i = 0; i < dataBeanListold.size(); i++) {
                    dataBeanListold.get(i).setLayoutId(BillActivity.IncomeAdapter.LAYOUT_ID);
                }
                dataBeanList.addAll(dataBeanListold);
                manager.setData(dataBeanList);
            }

        } else {
            showToast(stakingOrderHistoryData.getMsg());
        }

        if (dataBeanList.size() == 0) {
            recyclerView.setVisibility(View.GONE);
            nodatashowBody.setVisibility(View.VISIBLE);
        } else {
            nodatashowBody.setVisibility(View.GONE);
            recyclerView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void jumpToLoginAct(int staue) {
        if (staue == 3) {
//            showToast(getString(R.string.common_relogin));
//            Intent intent = new Intent();
//            intent.setAction(ConStant.EXIT_APP);
//            sendBroadcast(intent);
//            startActivity(BlockWalletLoginActivity.class);
//            finish();
        } else if (staue == 4) {
//            showToast(getString(R.string.paypasw_hint_setpaypsw));
//            Intent intent = new Intent(this,PayPwdActivity.class);
//            intent.putExtra("PayPwdActivityType",PayPwdActivity.PAYPSW_SET);
//            startActivity(intent);
//            finish();
            showToSetPaypswDialog();
        } else if (staue == 666) {
            showToUpdata();
        }
    }

    @Override
    public void onError(String error) {

        showToast(getString(R.string.common_loaderrritry));
    }

    @Override
    public void ShowProgress() {
        showWaitDialog();
    }

    @Override
    public void hideProgress() {
        hideWaitDialog();
    }


    @Override
    public void getStakingAddOrderData(StakingOrderAddData stakingOrderAddData) {

    }

    @Override
    public void getStakingCancelQueuingData(RegisterData registerData) {

    }

    @Override
    public void getStakingPayOrderData(RegisterData registerData) {

    }

    @Override
    public void getStakingOrderAppendData(StakingOrderAppendData appendData) {

    }

    @Override
    public void getStakingMiningMoneyDrawIndexData(StakingMiningMoneyDrawIndexData stakingMiningMoneyDrawIndexData) {

    }


    public class IncomeAdapter extends BaseAdapter<StakingOrderHistoryData.DataBean.ListBean> {

        public static final int LAYOUT_ID = R.layout.item_income_expend;

        public IncomeAdapter(@NonNull Context context) {
            super(context);
        }

        @Override
        protected void convert(BaseViewHolder helper, StakingOrderHistoryData.DataBean.ListBean dataBean, int itemType) {
            if (dataBean == null)
                return;
//            ImageView icomImg = helper.getView(R.id.icon);
//            GlideApp.with(context).load(dataBean.getMoneyTypeIcon()).error(R.drawable.icon_arctic)
//                    .into(icomImg);

            helper.setText(R.id.tv_channelType, dataBean.getChannelTypeName() + "");
            helper.setText(R.id.tv_createTime, dataBean.getDate());//CommonUtil.getDateTimeFromMillisecond(dataBean.getUpdateTime() != 0 ? dataBean.getUpdateTime() : dataBean.getCreateTime())
            double money = dataBean.getMoney();
            if (money < 0) {
                helper.setTextColor(R.id.tv_money, getResources().getColor(R.color.lehuobao_zhichu));
                helper.setImageDrawable(R.id.icon, getResources().getDrawable(R.drawable.icom_outdown));
                helper.setText(R.id.tv_money, CommonUtil.saveToPoint4WithNo(money));
            } else {
                helper.setTextColor(R.id.tv_money, getResources().getColor(R.color.colorgreen1));

                helper.setImageDrawable(R.id.icon, getResources().getDrawable(R.drawable.icom_getup));
                helper.setText(R.id.tv_money, "+" + CommonUtil.saveToPoint4WithNo(money));
            }
        }

    }

    public void showPopupMenu1(View view) {
        //参数View 是设置当前菜单显示的相对于View组件位置，具体位置系统会处理
        PopupMenu popupMenu = new PopupMenu(this, view);
        //加载menu布局
        Menu menu = popupMenu.getMenu();
        for (MiningWalletTypeIndexData.DataBean.ChannelListBean channelListBean : channelListBeans) {
            if (!tabName1.equalsIgnoreCase(channelListBean.getName())) {
                menu.add(channelListBean.getName());
            }
        }
        popupMenu.getMenuInflater().inflate(R.menu.menu_popmenu, menu);
//        popupMenu.set

        //设置menu中的item点击事件
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {

                for (int i = 0; i < channelListBeans.size(); i++) {
                    if (item.getTitle().toString().equalsIgnoreCase(channelListBeans.get(i).getName())) {
                        if (channelListBeansType != channelListBeans.get(i).getType()) {
                            channelListBeansType = channelListBeans.get(i).getType();//0 全部  1 2 3
                            channelType = channelListBeansType == 0 ? "" : channelListBeansType + "";
                            tabName1 = item.getTitle().toString();
                            tab.setTabTitle(0, item.getTitle().toString());
                            mathRequest();
                        }
                        break;
                    }
                }
                return true;
            }
        });
        popupMenu.setOnDismissListener(new PopupMenu.OnDismissListener() {
            @Override
            public void onDismiss(PopupMenu menu) {
                // 控件消失时的事件
            }
        });


        popupMenu.show();
    }

    ////    channelListBeansType,moneyTypeListBeansType,incomeTypeListBeansType
    public void showPopupMenu3(View view) {
        //参数View 是设置当前菜单显示的相对于View组件位置，具体位置系统会处理
        PopupMenu popupMenu = new PopupMenu(this, view);
        //加载menu布局
        Menu menu = popupMenu.getMenu();
        for (MiningWalletTypeIndexData.DataBean.IncomeTypeListBean incomeTypeListBean : incomeTypeListBeans) {
            if (!tabName3.equalsIgnoreCase(incomeTypeListBean.getName())) {
                menu.add(incomeTypeListBean.getName());
            }
        }
        popupMenu.getMenuInflater().inflate(R.menu.menu_popmenu, menu);


        //设置menu中的item点击事件
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {

                for (int i = 0; i < incomeTypeListBeans.size(); i++) {
                    if (item.getTitle().toString().equalsIgnoreCase(incomeTypeListBeans.get(i).getName())) {

                        if (incomeTypeListBeansType != incomeTypeListBeans.get(i).getType()) {
                            incomeTypeListBeansType = incomeTypeListBeans.get(i).getType();//0 全部  1 2 3
                            incomeType = incomeTypeListBeansType == 0 ? "" : incomeTypeListBeansType + "";
                            tabName3 = item.getTitle().toString();
                            tab.setTabTitle(1, item.getTitle().toString());
                            mathRequest();
                        }
                        break;
                    }
                }
                return true;
            }
        });
        popupMenu.setOnDismissListener(new PopupMenu.OnDismissListener() {
            @Override
            public void onDismiss(PopupMenu menu) {
                // 控件消失时的事件
            }
        });
        popupMenu.show();
    }

}
